import React, { Component } from 'react'
import {Button,Card,message,Modal,Form,Table} from 'antd'
import { PlusOutlined,ArrowRightOutlined } from '@ant-design/icons'
import LinkButton from '@c/link-button'
import {reqCategorys,reqUpdateCategory, reqAddCategory} from '@api/category'
import AddForm from './components/AddForm'
import UpdateForm from './components/UpdateForm'


export default class list extends Component {
    AddForm = React.createRef()
    UpdateForm = React.createRef()

    state={
        // 一级分类列表
        categories: [
            { _id: '1', name: '胡彦斌', age: 32, address: '西湖区湖底公园1号', },
            { _id: '2', name: '小孩子', age: 42, address: '北京新潮哈布公园2号', },
          ],
        //   二级分类列表
        subCategories:[],
        parentName:'',
        parentId:'0',//当前需要显示的父类列表的父分类ID
        showStatus:'',//标识添加/更新的确认框是否显示，0；都不显示，1：显示添加，2：显示更新
        loading:false,
        
    }
    initColumns=()=>{
        // 初始化行头
        this.columns = [
            {
              title: '类别',
              dataIndex: 'name',
              key: 'name',
            },
            {
              title: '操作',
              width:350,
              render:(topic,rowData)=>{return (<span><LinkButton onClick={()=>this.showUpdateForm(topic)}>修改分类</LinkButton><LinkButton onClick={()=>this.showSubCategories(rowData)}>查看子分类</LinkButton></span>)}
            },
          ]
    }
    

    UNSAFE_componentWillMount(){
        this.initColumns()
    }    
 
//    异步获取一级/二级分类列表显示
    componentDidMount(){
        this.getCategories()
    }

    // 根据parentId判断渲染到父或子数组中
    getCategories=async(parentId)=>{
        parentId = parentId||this.state.parentId
        this.setState({loading:true})
        const result =  await reqCategorys(parentId)
        this.setState({loading:false})
        if(result.status===0){
         if(parentId==='0')
         this.setState({categories:result.data})
         else
         this.setState({subCategories:result.data})
        }else{
            message.warning('请求出错！')
        }
    }
    // 显示二级列表 
    showSubCategories=(rowData)=>{
        console.log(rowData);
        this.setState({
            parentId:rowData._id,
            parentName:rowData.name
        },()=>{
            console.log('parentId', this.state.parentId) 
            // 获取二级分类列表显示
            this.getCategories()
        }) //在状态更新且重新render()后执行
      
    }
    // 显示一级列表
    showCategories=()=>{
        this.setState({
            parentId: '0',
            parentName:'',
            subCategories:[]
        })
    }
  /*
  响应点击取消: 隐藏确定框
   */
    hideModal = () => {
        // 清除输入数据 重置表单信息
        this.setUpdateForm.current.resetFields()
        // 隐藏确认框
        this.setState({
        showStatus: 0
        })
    }

    showAddForm=(topic)=>{
        
        console.log(topic);
        this.setState({
            showStatus:1
        })
    }
    showUpdateForm=(rowData)=>{
         // 保存分类对象
        this.category = rowData
        this.setState({
            showStatus:2
        })
    }

    // 添加一个分类类别
    addCategory=async ()=>{
        // this.form.resetFields()
         // 隐藏确认框
        this.setState({showStatus: 0})
        const {categoryName,parentId} = this.AddForm.current.state.addValue
        console.log(categoryName,parentId);
        const result = await reqAddCategory(categoryName, parentId)
        if(result.status===0){
            if(parentId===this.state.parentId){
                this.getCategories()
            }else if(parentId==='0'){
                this.getCategories('0')
            }
            message.success('添加成功')
        }else{
            message.error('添加失败')
        }
        // 重置表单信息
        this.setAddForm.current.resetFields()
    }
    // 更新一个分类类别
    updateCategory=async()=>{
         
        this.setState({showStatus:0 })
        const categoryId = this.category._id
        const categoryName = this.UpdateForm.current.state.categoryName
        const result = await reqUpdateCategory({categoryId,categoryName})
        if(result.status===0){
            this.getCategories()
            message.success('更新成功')
        }else{
            message.error('更新失败')
        }
        // 重置表单信息
        this.setUpdateForm.current.resetFields()
    }
    render() {
        const {parentName,parentId,categories,subCategories,loading,showStatus}= this.state
        const category = this.category || {name:'-'} // 如果还没有指定一个空对象
        const title = parentId==='0'?'一级分类列表':(
            <span>
                <LinkButton onClick={this.showCategories}>一级分类列表</LinkButton>
                <ArrowRightOutlined />
                <span>{parentName}</span>
            </span>
        )
        const extra =(
            <Button type='primary' icon={<PlusOutlined/>} onClick={this.showAddForm}>
            {/* <Button type='primary'  onClick={this.showAddForm}> */}
                添加
            </Button>
        )
     
        return (
            <Card title={title} extra={extra} style={{ width: '100%' }}>
                <Table  rowKey='_id' dataSource={parentId==='0'?categories:subCategories} columns={this.columns} loading={loading} pagination={{defaultPageSize:8,showQuickJumper:true}} bordered/>
                <Modal  title="添加分类" visible={showStatus===1} onOk={this.addCategory} onCancel={this.hideModal} okText="确认" cancelText="取消">
                    <AddForm categories={categories} parentId={parentId} ref={this.AddForm} setAddForm={setAddForm=>this.setAddForm=setAddForm}/>
                </Modal> 
                {/* 添加了destroyOnClose属性 每次打开都重新初始化 */}
                <Modal destroyOnClose title="更新分类" visible={showStatus===2} onOk={this.updateCategory} onCancel={this.hideModal} okText="确认" cancelText="取消">
                    <UpdateForm categoryName={category.name} ref={this.UpdateForm} setUpdateForm={setUpdateForm=>this.setUpdateForm=setUpdateForm} />
                </Modal>
            </Card>
          
        )
    }
}
